:- module(dic_mapping,[]).


:- use_module('../ns').
:- use_module('../lib/t_record').
:- use_module('../p2r/match').
:- use_module(library('http/http_open')).

/**
 * Mapping between an Eurostat dictionnary 
 * and the corresponding RDF terms
 */

directory(Dir,URI) :-
	dic_file(D),
	dic_file_to_dim_id(D,T),
	atom_concat('schema/dimension/',T,Dir),
	ns:dic_ns(NS),
	atom_concat(NS,T,URI).
directory(Dir,URI) :-
	dic_file(D),
	dic_file_to_dim(D,T),
	atom_concat('dimension/',T,Dir),
	ns:dim_ns(NS),
	t_record:t_record(D,[IDT,_]),
	downcase_atom(IDT,ID),
	format(atom(URI),'~w~w#~w',[NS,T,ID]).

dic_file(File) :-
	expand_file_name('data/all_dic/en/*.dic',Dics),
	member(File,Dics).

dic_geo_file(File) :-
	expand_file_name('data/all_dic/en/geo.dic',Dics),
	member(File,Dics).

dic_file_to_dim_id(File,DimID) :-
	dic_file_to_dim(File,DimT),
	upper_case_first_char(DimT,DimID).
dic_file_to_dim(File,Dim) :-
	file_base_name(File,Base),
	atom_concat(DimT,'.dic',Base),
	downcase_atom(DimT,Dim).
upper_case_first_char(Atom,AtomU) :-
	atom_chars(Atom,[First|Rest]),
	char_type(FirstU,to_upper(First)),
	atom_chars(AtomU,[FirstU|Rest]).
	


match:
	(
	 ns:dic_ns(NS),
	 dic_mapping:dic_file(D),
	 dic_mapping:dic_file_to_dim_id(D,DimID)
	)
		eq
	[
		rdf(pattern([NS,DimID]),rdfs:subClassOf,riese:'Dimension')
	,	rdf(pattern([NS,DimID]),dc:title,literal(DimID)) % Not the best label ever :-)
	,	rdf(pattern([NS,DimID]),rdfs:label,literal(DimID))
	].

match:
	(
	 ns:dim_ns(DimNS),
	 ns:dic_ns(DicNS),
	 dic_mapping:dic_file(D),
	 dic_mapping:dic_file_to_dim(D,Dim),
	 dic_mapping:dic_file_to_dim_id(D,DimID),
	 t_record:t_record(D,[IDT,Label]),
	 downcase_atom(IDT,ID),ID\=''
	)
		eq
	[
		rdf(pattern([DimNS,Dim,'/',ID]),rdf:type,pattern([DicNS,DimID])) %NO BACKLINKS
	,	rdf(pattern([DimNS,Dim,'/',ID]),dc:title,literal(Label))
	,	rdf(pattern([DimNS,Dim,'/',ID]),rdfs:label,literal(Label))
	].
	
/**
 * Country mapping
 */
match:
	(
	 \+var(ID),
	 ns:dim_ns(DimNS),
	 dic_mapping:dic_geo_file(D),
	 dic_mapping:dic_file_to_dim(D,Dim),
	 %dic_mapping:dic_file_to_dim_id(D,DimID),
	 t_record:t_record(D,[IDT,_Label]),
	 downcase_atom(IDT,ID),
	 atom_length(ID,2),
	 dic_mapping:geonames_country(ID,URI)
	)
		eq
	[
		rdf(pattern([DimNS,Dim,'/',ID]),rdf:type,geo:'Country')
	,	rdf(pattern([DimNS,Dim,'/',ID]),owl:sameAs,URI)
	].
	

geonames_country(ID,URI) :-
	concat_atom(['http://ws.geonames.org/search?country=',ID,'&fclass=A','&type=rdf','&maxRows=1'],Url),
	http_open:http_open(Url,Stream,[]),
	load_rdf(Stream,Triples),
	close(Stream),
	member(rdf(URI,'http://www.w3.org/1999/02/22-rdf-syntax-ns#type','http://www.geonames.org/ontology#Feature'),Triples).
